package cn.isgrow.gateway.controller;

import cn.isgrow.gateway.entity.RouteDefinitionEntity;
import cn.isgrow.gateway.req.RouteDefinitionReq;
import cn.isgrow.gateway.service.MongoDynamicRouteService;
import cn.isgrow.gateway.service.RedisDynamicRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.Valid;
import java.net.URISyntaxException;
@Slf4j
//@CrossOrigin(methods = {RequestMethod.GET, RequestMethod.DELETE, RequestMethod.PUT, RequestMethod.POST, RequestMethod.OPTIONS}, origins = "http://localhost:8000'")
@RestController
@RequestMapping("/gateway/mongo/")
public class MongoDynamicRouteController {


    @Autowired private MongoDynamicRouteService mongoDynamicRouteService;

    @PostMapping("/add")
    public Mono<RouteDefinitionEntity> create(@Valid @RequestBody RouteDefinitionEntity entity) {
//        RouteDefinitionEntity entity = getRouteDefinitionEntity(req);
        entity.setId(null);
        Mono<RouteDefinitionEntity> add = mongoDynamicRouteService.add(entity);
        log.info("路由信息已保存");
        return add;
    }

    @PutMapping("/update/{id}")
    public Mono<RouteDefinitionEntity> update(@PathVariable("id") String id,
                                              @Valid @RequestBody RouteDefinitionEntity entity) {
        entity.setId(id);
        Mono<RouteDefinitionEntity> update = mongoDynamicRouteService.update(entity);
        return update;
    }

    @DeleteMapping("/delete/{id}")
    public Mono<ResponseEntity<Void>> delete(@PathVariable("id") String id) {
        return mongoDynamicRouteService.deleteById(id);
    }

    /**
     * 查询所有路由信息
     * @return
     */
    @GetMapping("/list")
    public  Flux<RouteDefinitionEntity> list() {
        return  mongoDynamicRouteService.findAll();
    }

    @GetMapping("/{id}")
    public  Mono<RouteDefinitionEntity> findById(@PathVariable String id) {
        return mongoDynamicRouteService.findById(id);
    }

    @GetMapping("/refresh")
    public  Mono<Void> refresh() {
        return mongoDynamicRouteService.refresh();
    }

}